package com.glodon.jcloud.increment.shorturl.aop;

import com.glodon.jcloud.increment.shorturl.service.ShortUrlService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * Create Date: 2022/12/13
 *
 * @version: V0.0.1-SNAPSHOT
 * @author: Terry.Li
 * @mail: lib-o@glodon.com
 */
@Aspect
@Order
@Component
public class ViewCountAop {

    @Resource
    private ShortUrlService shortUrlService;

    @Pointcut(value = "execution(public * com.glodon.jcloud.increment.shorturl.controller.ShortUrlController.redirect(..)) && args(alias, response)", argNames = "alias,response")
    public void redirectPointcut(String alias, HttpServletResponse response) {}

    @Around("redirectPointcut(alias, response)")
    public Object redirect(ProceedingJoinPoint pjp, String alias, HttpServletResponse response) {

        Object result = null;

        try {
            result = pjp.proceed();

            shortUrlService.view(alias);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

        return result;
    }

}
